import jwt from "jsonwebtoken"
import svgCaptcha from "svg-captcha"
import userService from "../service/user.service.js"
const { createUser, getUserInfo, updateById, saveUserData } = userService
import errType from "../constant/err.type.js"
const { userRegisterError, changePasswordError } = errType
class UserController {
  // 验证码
  async code(ctx, next) {
    try {
      // 生成加法形式的验证码
      // var captcha = svgCaptcha.createMathExpr({
      //     fontSize:50,
      //     width:120,
      //     height:34,
      //     background:'#cc9966'
      // });

      // 生成验证码
      var captcha = svgCaptcha.create({
        size: 4,
        fontSize: 50,
        width: 100,
        height: 40,
        noise: 4,
        background: "#cc9966",
      })
      // 保存生成的验证码结果
      ctx.session.code = captcha.text.toLowerCase()
      const img = new Buffer.from(captcha.data).toString("base64") // 验证码
      const base64Img = "data:image/svg+xml;base64," + img
      ctx.echo({
        codeImg: base64Img,
      })
    } catch (error) {
      console.error(error)
    }
  }

  // 注册
  async register(ctx, next) {
    const { user_name, password } = ctx.request.body
    try {
      await createUser(user_name, password)
      ctx.body = {
        code: 200,
        msg: "用户注册成功",
      }
    } catch (error) {
      console.error(error)
      userRegisterError.data = error
      ctx.app.emit("error", userRegisterError, ctx)
    }
  }

  // 登录
  async login(ctx, next) {
    const { user_name } = ctx.request.body
    try {
      const { password, ...res } = await getUserInfo({ user_name })
      ctx.body = {
        code: 200,
        msg: "登录成功",
        data: {
          token: jwt.sign(res, process.env.JWT_SECRET, { expiresIn: "1d" }),
        },
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 修改密码
  async changePassword(ctx, next) {
    const id = ctx.state.user.id
    const password = ctx.request.body.password
    try {
      if (await updateById({ id, password })) {
        ctx.echo({ msg: "密码修改成功" })
      } else {
        ctx.echo(changePasswordError)
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 保存用户资料
  async saveUserInfo(ctx, next) {
    const { user_name, password } = ctx.request.body
    try {
      await saveUserData({ user_name, password })
      ctx.echo()
    } catch (error) {
      console.error(error)
    }
  }
}

export default new UserController()
